import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/person_detail/bean/person_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/person_detail/widgets/person_artificial_attendance_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

class ArtificialAttendanceWidget extends StatefulWidget {
  final FaceUserInfoBean faceUserInfoBean;

  const ArtificialAttendanceWidget({Key key, this.faceUserInfoBean})
      : super(key: key);

  @override
  _ArtificialAttendanceWidgetState createState() =>
      _ArtificialAttendanceWidgetState();

  ///跳转方法
  ///markedInfoBean 提前缓存加载（需要通用修改重构）
  static Future<dynamic> navigatorPush(
      BuildContext context, FaceUserInfoBean faceUserInfoBean) {
    return RouterUtils.routeForFutureResult(
      context,
      ArtificialAttendanceWidget(
        faceUserInfoBean: faceUserInfoBean,
      ),
    );
  }
}

class _ArtificialAttendanceWidgetState
    extends BaseState<ArtificialAttendanceWidget> {
  Color defaultColor = Color(0xFF808388);
  TextEditingController _editingController;
  var _nowDate = DateTime.now(); //获取当前时间
  var _nowHMDate = DateTime.now(); //获取当前时间
  Color textColor = Color(0xFF5E687C);
  PersonArtificialAttendanceViewModel viewModel;
  bool isSameMonth = false;
  var  lastPopTime;
  @override
  void initState() {
    super.initState();
    lastPopTime = DateTime.now().add(Duration(minutes: -1));
    _editingController = TextEditingController();
    viewModel = PersonArtificialAttendanceViewModel(this);
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: _artificialAttendancePage(),
    );
  }

  Widget _artificialAttendancePage() {
    return Column(
      children: [
        _toTopBarWidget(),
        _detailedInformationWidget(),
      ],
    );
  }

  Widget _detailedInformationWidget() {
    String nameAndNick = "";
    if (widget?.faceUserInfoBean?.nick != null &&
        widget?.faceUserInfoBean?.nick != "") {
      nameAndNick =
          widget?.faceUserInfoBean?.name + "/" + widget?.faceUserInfoBean?.nick;
    } else {
      nameAndNick = widget?.faceUserInfoBean?.name;
    }

    if(DateTime.now().year ==  _nowDate.year&&
        DateTime.now().month == _nowDate.month &&
        DateTime.now().day == _nowDate.day){
      isSameMonth = true;
    }else isSameMonth = false;

    return Column(
      children: [
        Container(
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          height: 50,
          child: Row(
            children: [
              SizedBox(
                width: 15,
              ),
              Text(
                "姓名",
                style: TextStyle(color: defaultColor, fontSize: 14),
              ),
              SizedBox(
                width: 15,
              ),
              Text(
                "${nameAndNick??""}",
                style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 14),
              ),
            ],
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(left: 15),
          child: Divider(
            height: 1,
            color: Color(0xFF3A3F50),
          ),
        ),
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            // _cupertinoPicker();
          },
          child: Container(
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            height: 50,
            child: Row(
              children: [
                SizedBox(
                  width: 15,
                ),
                Text(
                  "日期",
                  style: TextStyle(color: defaultColor, fontSize: 14),
                ),
                SizedBox(
                  width: 15,
                ),
                Text(isSameMonth ? "${_nowDate.toString().substring(0, 10)}（今天）" :
                "${_nowDate.toString().substring(0, 10)}",
                  style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 14),
                ),
                Spacer(),
                Spacer(),
                // Image.asset(
                //   "images/go_ico.png",
                //   width: 6,
                //   color: VgColors.DEFAULT_FIELD_COLOR,
                // ),
                SizedBox(
                  width: 15,
                ),
              ],
            ),
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(left: 15),
          child: Divider(
            height: 1,
            color: Color(0xFF3A3F50),
          ),
        ),
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            _minutePicker();
          },
          child: Container(
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            height: 50,
            child: Row(
              children: [
                SizedBox(
                  width: 15,
                ),
                Text(
                  "时间",
                  style: TextStyle(color: defaultColor, fontSize: 14),
                ),
                SizedBox(
                  width: 15,
                ),
                Text(
                  "${_nowHMDate.hour.toString().padLeft(2,"0")}:${_nowHMDate.minute.toString().padLeft(2,"0")}",
                  style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 14),
                ),
                Spacer(),
                Spacer(),
                Image.asset(
                  "images/go_ico.png",
                  width: 6,
                  color: VgColors.DEFAULT_FIELD_COLOR,
                ),
                SizedBox(
                  width: 15,
                ),
              ],
            ),
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(left: 15),
          child: Divider(
            height: 1,
            color: Color(0xFF3A3F50),
          ),
        ),
        Container(
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          height: 80,
          alignment: Alignment.topLeft,
          child: Row(
            children: [
              SizedBox(
                width: 15,
              ),
              Container(
                  alignment: Alignment.topLeft,
                  padding: const EdgeInsets.only(top: 15),
                  child: Text(
                "备注",
                style: TextStyle(color: defaultColor, fontSize: 14),
              )),
              SizedBox(
                width: 15,
              ),
              Expanded(
                child: VgTextField(
                  controller: _editingController,
                  maxLines: 4,
                  minLines: 4,
                  maxLength: 50,
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    counterText: "",
                    contentPadding: const EdgeInsets.only(top: 15),
                    hintText: "选填",
                    hintStyle: TextStyle(
                        color: ThemeRepository.getInstance()
                            .getTextEditHintColor_3A3F50(),
                        fontSize: 14),
                  ),
                  style: TextStyle(
                      fontSize: 14,
                      color: ThemeRepository.getInstance()
                          .getTextMainColor_D0E0F7()),
                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 12,),
        Container(
          padding: const EdgeInsets.only(left: 15),
          child: Row(
            children: [
              Text(
                "操作人：",
                style: TextStyle(color: textColor, fontSize: 12),
              ),
              Text(
                "${UserRepository.getInstance().userData.comUser.name ?? ""}",
                style: TextStyle(color: textColor, fontSize: 12),
              ),
              SizedBox(width: 5,),
              Text(
                "${_nowDate.month}月${_nowDate.day}日 ${_nowHMDate.hour.toString().padLeft(2,"0")}:${_nowHMDate.minute.toString().padLeft(2,"0")}",
                style: TextStyle(color: textColor, fontSize: 12),
              ),
            ],
          ),
        ),
      ],
    );
  }

  _minutePicker(){
    DatePicker.showDatePicker(context,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        backgroundColor:
        ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        confirm: Text('确定', style: TextStyle(color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
        cancel: Text('取消', style: TextStyle(color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
        itemTextStyle: TextStyle(color: Colors.white),
      ),
      // minDateTime:DateTime.parse(_isTodayTime()),//最小值
      maxDateTime:DateTime.parse(_isTodayTime()),
      initialDateTime:_nowHMDate,//默认日期
//                             dateFormat:'MM'+'月'+' '+'dd'+'日'+' '+'HH时'+'mm分',//显示时间格式
      dateFormat:'HH时:mm分',

      locale:DateTimePickerLocale.zh_cn,
      pickerMode:DateTimePickerMode.datetime,//选择器种类
      // onChange:(data,i){print(data);},
      onConfirm:(data,i){
          _nowHMDate = data;
          setState(() { });
      },
    );
  }

  //是否是当天
  String _isTodayTime(){
    if(_nowDate?.toString()?.substring(0,10) == DateTime.now().toString()?.substring(0,10)){
      return DateTime.now().toString();
    }else{
      return _nowDate?.toString()?.substring(0,10);
    }

  }

  _cupertinoPicker(){
    DatePicker.showDatePicker(
      context,
      pickerTheme: DateTimePickerTheme(
        backgroundColor:
        ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        showTitle: true,
        confirm: Text('确定', style: TextStyle(color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
        cancel: Text('取消', style: TextStyle(color: ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
        itemTextStyle: TextStyle(color: Colors.white),
      ),
      minDateTime: DateTime.parse('2010-01-01'), //起始日期
      maxDateTime: DateTime.parse(DateTime.now().toString()), //终止日期
      initialDateTime: _nowDate, //当前日期
      dateFormat: 'yyyy-MMMM-dd',  //显示格式
      locale: DateTimePickerLocale.zh_cn, //语言 默认DateTimePickerLocale.en_us
      onClose: () => print("----- onClose -----"),
      onCancel: () => print('onCancel'),
      onConfirm: (dateTime, List<int> index) { //确定的时候
        setState(() {
          _nowDate = dateTime;
        });
      },
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
        title: "手动打卡", isShowBack: true, rightWidget: _buttonWidget());
  }

  Widget _buttonWidget() {
    return Container(
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: true,
        width: 48,
        height: 24,
        unSelectBgColor:
            ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
          color: VgColors.INPUT_BG_COLOR,
          fontSize: 12,
        ),
        selectedTextStyle: TextStyle(
          color: Colors.white,
          fontSize: 12,
        ),
        text: "确认",
        onTap: () {
          if(!(intervalClick(2) ?? false)){
            return null;
          }
          viewModel.manualAddFacePunchInfo(context, widget?.faceUserInfoBean?.fuid,
              widget?.faceUserInfoBean?.fid,
              _nowDate?.toString()?.substring(0,10)+" "+_nowHMDate.hour?.toString()?.padLeft(2,"0")+":"+_nowHMDate.minute?.toString()?.padLeft(2,"0"),
              _editingController?.text);
        },
      ),
    );
  }

  bool intervalClick(int needTime){
    // 防重复提交
    if(lastPopTime == null || DateTime.now().difference(lastPopTime) > Duration(seconds: needTime)){
      lastPopTime = DateTime.now();
      print("允许点击");
      return true;
    }else{
      // lastPopTime = DateTime.now(); //如果不注释这行,则强制用户一定要间隔2s后才能成功点击. 而不是以上一次点击成功的时间开始计算.
      print("请勿重复点击！");
      return false;
    }
  }
}
